#include "button.h"
#include <QPainter>
#include <QPaintEvent>
#include <QMouseEvent>
#include <QMessageBox>

Button::Button(QDialog *parent, int row, int col) :
        QPushButton(parent), state(EMPTY), m_row(row), m_col(col)
{
    setMinimumSize(QSize(50, 50));
    setMaximumSize(QSize(200, 200));
    setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Maximum);

    connect(this, SIGNAL(getState(int, int)), parent, SLOT(getState(int, int)));
    connect(this, SIGNAL(checkWinner()), parent, SLOT(getWinner()));
}

void Button::paintEvent(QPaintEvent *e)
{
    QPainter painter(this);

    switch (state)
    {
    case ZERO:
        painter.setBrush(Qt::blue);
        painter.setBrush(Qt::NoBrush);
        painter.drawEllipse(e->rect());
        break;
    case CROSS:
        int x1, y1, x2, y2;
        painter.setBrush(Qt::red);
        e->rect().getCoords(&x1, &y1, &x2, &y2);
        painter.drawLine(x1, y1, x2, y2);
        painter.drawLine(x1, y2, x2, y1);
        break;
    case EMPTY:
        break;
    }
}

void Button::mousePressEvent(QMouseEvent*)
{
    if (state == EMPTY)
    {
        state = getState(m_row, m_col);
        update();

        if (state != EMPTY)
        {
            States winner = checkWinner();
            if (winner != EMPTY)
            {
                QString s(winner == CROSS ? "Crosses win!" : "Zeroes win!");
                QMessageBox msg;
                msg.setText(s);
                msg.exec();
            }
        }
    }
}
